#!/usr/bin/python3 -u

'''
    This script removes unreferenced builds from s3 bucket
'''

import argparse
import sys
import os

from cosalib.builds import Builds
from cosalib.prune import fetch_build_meta, get_unreferenced_s3_builds, delete_build

parser = argparse.ArgumentParser(prog="coreos-assembler remote-prune")
parser.add_argument("--workdir", default='.', help="Path to workdir")
parser.add_argument("--dry-run", help="Don't actually delete anything",
                    action='store_true')
parser.add_argument('--azure-credentials', help='Path to Azure credentials file',
                    default=os.environ.get("AZURE_CREDENTIALS"))
parser.add_argument('--azure-resource-group', help='Resource group',
                    default=os.environ.get('AZURE_RESOURCE_GROUP'))
parser.add_argument("--gcp-json-key", help="GCP Service Account JSON Auth",
                    default=os.environ.get("GCP_JSON_AUTH"))
parser.add_argument("--gcp-project", help="GCP Project name",
                    default=os.environ.get("GCP_PROJECT_NAME"))

subparsers = parser.add_subparsers(dest='cmd', title='subcommands')
subparsers.required = True

s3 = subparsers.add_parser('s3', help='Prune s3 buckets')
s3.add_argument("--bucket", help="Bucket name")
s3.add_argument("--prefix", help="Key prefix")
s3.add_argument("--force", help="Wipe s3 key ignoring the errors",
                action='store_true')

args = parser.parse_args()

builds = Builds(args.workdir)

scanned_builds = []
for build in builds.raw()["builds"]:
    for arch in build['arches']:
        build = fetch_build_meta(builds, build['id'], arch, args.bucket, args.prefix)
        if build:
            scanned_builds.append(build)

new_builds = []
builds_to_delete = []

# Find unreferenced builds in the bucket and remove them
buildids = [x.id for x in scanned_builds]
unreferenced_s3_builds = get_unreferenced_s3_builds(buildids, args.bucket, args.prefix)

if args.dry_run:
    print("Not removing anything: in dry-run mode")
    sys.exit(0)

cloud_config = {
    'azure': {
        'credentials': args.azure_credentials,
        'resource-group': args.azure_resource_group,
    },
    'gcp': {
        'json-key': args.gcp_json_key,
        'project': args.gcp_project,
    }
}

error_during_pruning = False
for unmatched_build_id in unreferenced_s3_builds:
    # TODO: fetch arches from s3
    build = fetch_build_meta(builds, unmatched_build_id, 'x86_64', args.bucket, args.prefix)
    if build:
        try:
            delete_build(build, args.bucket, args.prefix, cloud_config, args.force)
        except Exception as e:
            error_during_pruning = True
            print(f"{e}")

if error_during_pruning:
    sys.exit(1)
